<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Helper\CookieHelper;
use App\Helper\JwtHelper;
use App\Helper\RequestHelper;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CoreMiddleware extends \Hyperf\HttpServer\CoreMiddleware
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = parent::process($request, $handler);
        $guestJwt = JwtHelper::decodeWithRequest(JwtHelper::GUEST_JWT_TOKEN, $request);
        if (!is_null($guestJwt)) {
            return $response;
        }
        $jwtString = JwtHelper::encode(RequestHelper::getClientIp($request));
        $cookie = CookieHelper::genOne(JwtHelper::GUEST_JWT_TOKEN, $jwtString, 86400 * 200);
        return $response->withCookie($cookie);
    }

    protected function handleNotFound(ServerRequestInterface $request)
    {
        if (RequestHelper::isAjax($request)) {
            return $this->response()->withStatus(404);
        }
        return $this->response()->withStatus(302)->withAddedHeader('Location', '/404.html');
    }
}
